package org.jeecg.modules.iot.aio.task.base;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 这里是一个注释
 *
 * @author scw
 * @version v1.0
 * @date
 */
public abstract class BaseRunnable implements Runnable{

    private static Logger log = LoggerFactory.getLogger(BaseRunnable.class);

    private ThreadPoolExecutor executor;

    protected ReentrantLock runningLock = new ReentrantLock();

    private boolean isCanceled = false;
    public boolean executed = false;
    public BaseRunnable(ThreadPoolExecutor executor){this.executor = executor;}

    public void execute(){this.executor.execute(this);}

    public abstract void runTask();
    public abstract boolean isNeededExecute();

    public boolean isCanceled() {
        return this.isCanceled;
    }

    @Override
    public void run() {
        if (!this.isCanceled()) {
            boolean tryLock = false;
            try {
                tryLock = this.runningLock.tryLock(1L, TimeUnit.SECONDS);
            } catch (InterruptedException var7) {
                log.error(var7.toString(), var7);
            }
            if (tryLock) {
                try {
                    int loopCount = 0;
                    this.runTask();
                    while(this.isNeededExecute() && loopCount++ < 100) {
                        this.runTask();
                    }
                } catch (Throwable var8) {
                    log.error(var8.toString(), var8);
                } finally {
                    this.executed = false;
                    this.runningLock.unlock();
                }
            } else {
                this.executed = false;
            }
        }
    }

    public void setIsCancel(boolean isCanceled){
        this.isCanceled = isCanceled;
    }

}
